# @shuaige : 陈世玉
# @name :Data_analysis.py
# @time :2024/12/6 20:12
# @shuaige : 陈世玉
# @name : Data_analysis.py
# @time : 2024/12/6 19:54

from pyecharts.charts import Pie, Grid
from pyecharts import options as opts

# 读取文件内容
with open('data1.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
# 初始化一个字典来存储各类院校的数量
def type_analysis(lines):
    type_count = {}
    # 解析每一行数据并统计类型数量
    for line in lines[0:]:
        parts = line.split()
        university_type = parts[3]  # 第四个字段是院校类型

        if university_type in type_count:
            type_count[university_type] += 1
        else:
            type_count[university_type] = 1

    # 提取院校类型和数量
    attr = list(type_count.keys())
    v1 = list(type_count.values())
    # 生成饼图-玫瑰图
    pie_type = Pie()
    pie_type.add(
        "各类院校",
        [list(z) for z in zip(attr, v1)],
        center=["74%", "50%"],
        radius=["30%", "60%"],
        rosetype="radius",
    )
    pie_type.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
    return pie_type

# 初始化一个字典来存储各省份的大学数量
def province_analysis(lines):
    province_count = {}

    # 解析每一行数据并统计省份数量
    for line in lines[0:]:  # 跳过第一行标题
        parts = line.split()
        province = parts[2]  # 第三个字段是省份
        if province in province_count:
            province_count[province] += 1
        else:
            province_count[province] = 1
    # 提取省份和数量
    attr = list(province_count.keys())
    v1 = list(province_count.values())

    # 生成饼图-玫瑰图
    pie_province = Pie()
    pie_province.add(
        "各省份大学",
        [list(z) for z in zip(attr, v1)],
        center=["28%", "50%"],
        radius=["30%", "60%"],
        rosetype="radius",
    )
    pie_province.set_series_opts(label_opts=opts.LabelOpts(
        formatter="{b}: {c} ({d}%)"))

    return pie_province

# 主函数
def main():
    # 读取文件内容
    with open('data1.txt', 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 生成各类院校占比图
    pie_type = type_analysis(lines)

    # 生成各省份大学占比图
    pie_province = province_analysis(lines)

    # 使用Grid将两个图表组合在一起
    grid = Grid(init_opts=opts.InitOpts(width="1500px", height="800px"))
    grid.add(pie_type, grid_opts=opts.GridOpts(pos_left="20%"))
    grid.add(pie_province, grid_opts=opts.GridOpts(pos_right="50%"))
    # 渲染图表到HTML文件
    grid.render("university_distribution.html")

if __name__ == "__main__":
    main()
